package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.user.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.TemplateApi;
import com.jmp.base.dto.SeeRecordGoodsListRequest;
import com.jmp.base.dto.SeeRecordGoodsRequest;
import com.jmp.base.dto.TemplateGet2Request;
import com.jmp.base.dto.TemplateGetResponse;
import com.jmp.feign.SeeRecordFeign;
import com.jmp.feign.TemplateFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.ConvertUtils;
import one.stand.mapper.GoodSpecMapperExt;
import one.stand.mapper.GoodsApiUserMapper;
import one.stand.model.*;
import one.stand.request.GoodSpecRequest;
import one.stand.request.GoodsRequest;
import one.stand.response.GoodSpecResponse;
import one.stand.service.*;
import one.stand.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 产品信息查询
 *
 * @author Administrator
 */
@RestController
@RequestMapping("userApi/goods")
@Api(description = "产品系列")
public class GoodsController extends BaseController {
    @Autowired
    private SeeRecordFeign seeRecordFeign;
    @Autowired
    private TemplateFeign templateFeign;

    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private GoodSpecMapperExt goodSpecMapperExt;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private WebsiteService websiteService;

    @Autowired
    private GoodsApiUserMapper goodsApiUserMapper;

    @ApiOperation(value = "查询公司信息-动态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "公司ID", required = true, paramType = "Integer"),
    })
    @PostMapping("/getCompanyInfo")
    public ResultModel<CompanyInfoResponse> getCompanyInfo(@RequestAttribute CompanyInfoRequest request) {
        AssertUtil.isTrue(Objects.nonNull(request) && Objects.nonNull(request.getCompanyId()), ResultEnum.PARAM_CHECK);

        Company companyModel = companyBaseService.getById(request.getCompanyId());
        AssertUtil.nonNull(companyModel, ResultEnum.NO_DATA);

        Website website = websiteService.getByCompanyId(request.getCompanyId());
        String companyPhoto = StringUtils.EMPTY;
        if (Objects.nonNull(website) && StringUtils.isNoneBlank(website.getPhotos())) {
            companyPhoto = website.getPhotos().split(",")[0];
        }

        CompanyInfoResponse response = CompanyInfoResponse.builder()
                .companyLogo(companyModel.getCompanyLogo())
                .companyName(companyModel.getCompanyName())
                .companyPhoto(companyPhoto)
                .build();
        return ResultModel.success(response);
    }

    @PostMapping("/company/info")
    @ApiOperation(value = "查询公司信息-产品列表")
    @SecurityAuthCheck
    public ResultModel<GoodsCompanyInfoResponse> companyInfo(@RequestAttribute CompanyInfoRequest request) {
        AssertUtil.isTrue(Objects.nonNull(request) && Objects.nonNull(request.getCompanyId()), ResultEnum.PARAM_CHECK);

        String key = "company:" + request.getCompanyId();
        GoodsCompanyInfoResponse responseResultModel = redisUtil.get(key);
        if (Objects.nonNull(responseResultModel)) {
            return ResultModel.success(responseResultModel);
        }

        Company companyModel = companyBaseService.getById(request.getCompanyId());
        AssertUtil.nonNull(companyModel, ResultEnum.NO_DATA);

        Website website = websiteService.getByCompanyId(request.getCompanyId());
        String companyPhoto = StringUtils.EMPTY;
        if (Objects.nonNull(website) && StringUtils.isNoneBlank(website.getPhotos())) {
            companyPhoto = website.getPhotos().split(",")[0];
        }

        final Integer isCollection = recordPublicService.isCollection(request.getId(), RecordPublicService.ITEMTYPE_COMPANY, request.getCompanyId()) ? 1 : 2;

        List<GoodsType> goodstypeModelList = goodsApiUserMapper.selectTypes(companyModel.getCompanyId());
        List<GoodsCompanyInfoResponse.Type> types = OneListUtil.group(goodstypeModelList,
                goodsType -> goodsType.getParentId() == 0,
                GoodsType::getGoodstypeId,
                GoodsType::getParentId,
                (parent, child) -> parent.getChildList().add(child),
                goodsType -> GoodsCompanyInfoResponse.Type.builder()
                        .goodstypeId(goodsType.getGoodstypeId())
                        .name(goodsType.getName())
                        .childList(Lists.newLinkedList())
                        .build(),
                goodsType -> GoodsCompanyInfoResponse.Type.builder()
                        .goodstypeId(goodsType.getGoodstypeId())
                        .name(goodsType.getName())
                        .build());

        GoodsCompanyInfoResponse response = GoodsCompanyInfoResponse.builder()
                .userLogo(null)
                .companyLogo(companyModel.getCompanyLogo())
                .companyName(companyModel.getCompanyName())
                .showRoomState(CompanyBaseService.SHOWROOMSTATE_OPEN.equals(companyModel.getShowroomstate()))
                .isCollection(isCollection)
                .goodstypeModelList(types)
                .companyPhoto(companyPhoto)
                .build();

        redisUtil.set(key, response, 5, TimeUnit.MINUTES);
        return ResultModel.success(response);
    }

    /**
     * 疑似不在使用
     */
    @ApiOperation(value = "根据公司查询产品分类")
    @PostMapping("/getGoodsType")
    @SecurityAuthCheck
    @Deprecated
    public ResultModel<List<GoodsTypeResponse>> getGoodsType(GoodsTypeRequest request) {

        Company companyModel = companyBaseService.getById(request.getCompanyId());
        AssertUtil.nonNull(companyModel, "企业不存在");

        List<GoodsType> list = goodsTypeService.getParent(request.getCompanyId());

        List<GoodsTypeResponse> response = ConvertUtils.list(list, goodstypeModel -> GoodsTypeResponse.builder()
                .companyId(request.getCompanyId())
                .companyName(companyModel.getCompanyName())
                .companyLogo(companyModel.getCompanyLogo())
                .goodstypeId(goodstypeModel.getGoodstypeId())
                .name(goodstypeModel.getName())
                .build());
        return ResultModel.success(response);
    }

    @ApiOperation(value = "根据产品分类查询产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodstypeId", value = "产品分类ID", paramType = "Integer"),
    })
    @PostMapping("/getGoodsList")
    @SecurityAuthCheck
    public ResultModel getGoodsList(@RequestAttribute GoodsRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        }

        String key = "goodsList:" + request.getCompanyId() + ":" + request.getGoodstypeId() + ":" + request.getGoodsName() + ":" + request.getPageNum() + ":" + request.getPageSize();
        List<GoodsListResponse> resultModel = redisUtil.get(key);
        if (request.getPageNum() == 1 && Objects.nonNull(resultModel)) return ResultModel.success(resultModel);

        List<Integer> typeIds = null;
        if (Objects.nonNull(request.getGoodstypeId()) && request.getGoodstypeId() > 0) {
            typeIds = Lists.newArrayList(request.getGoodstypeId());
            List<GoodsType> goodsTypes = goodsTypeService.getChild(request.getGoodstypeId(), null);
            if (OneListUtil.isNotEmpty(goodsTypes)) {
                for (GoodsType goodsType : goodsTypes) {
                    typeIds.add(goodsType.getGoodstypeId());
                }
            }
        }
        String goodsNameLike = SqlUtil.like(request.getGoodsName());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Goods> list = goodsApiUserMapper.selectGoodsInfo(request.getCompanyId(), typeIds, goodsNameLike);
        if (list == null || list.size() < 1) {
            return ResultModel.noData();
        }

        boolean fal = request.getMyCardId() == null || !request.getMyCardId().equals(request.getCardId());
        if (fal) {
            //添加查看记录
            SeeRecordGoodsListRequest recordGoodsListRequest = SeeRecordGoodsListRequest.builder()
                    .userId(request.getId().intValue())
                    .cardId(request.getCardId())
                    .build();
            seeRecordFeign.goodsList(recordGoodsListRequest);
        }

        List<GoodsListResponse> responses = ConvertUtils.list(list, goodsModel -> GoodsListResponse.builder()
                .goodsId(goodsModel.getGoodsId())
                .goodsName(goodsModel.getGoodsName())
                .goodPhoto(StringUtils.join(goodsPhotoService.getListPath(goodsModel.getGoodsId()), OneConstant.arraySymbol))
                .price(MoneyUtil.getMoneyInt(goodsModel.getPrice()))
                .showPrice(goodsModel.getShowPrice())
                .coverType(StringUtils.isNoneBlank(goodsModel.getQjVrUrl()) ? 1 : (StringUtils.isNoneBlank(goodsModel.getVideoUrl()) ? 2 : 0))
                .build());

        if (request.getPageNum() == 1) {
            redisUtil.set(key, responses, 5, TimeUnit.MINUTES);
        }
        return ResultModel.success(responses);
    }

    @ApiOperation(value = "根据产品查询规格")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "产品ID", required = true, paramType = "Integer"),
    })
    @PostMapping("/getGoodSpec")
    @SecurityAuthCheck
    public ResultModel getGoodSpec(@RequestAttribute GoodSpecRequest request) {
        GoodSpecModel model = new GoodSpecModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        List<GoodSpecModel> list = goodSpecMapperExt.getSpec(model);
        if (list == null || list.size() < 1) {
            return ResultModel.noData();
        }
        List<GoodSpecResponse> responseList = new ArrayList<>();
        list.forEach(obj -> {
            {
                GoodSpecResponse response = new GoodSpecResponse();
                BeanUtils.copyProperties(obj, response);
                responseList.add(response);
            }
        });
        return ResultModel.success(responseList);
    }

    @ApiOperation(value = "查询产品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId", value = "产品ID", required = true, paramType = "Integer"),
    })
    @PostMapping("/getGoodsInfo")
    @SecurityAuthCheck
    public ResultModel<GoodsInfoResponse> getGoodsInfo(@RequestAttribute GoodsInfoRequest request) {
        if (request == null || request.getGoodsId() <= 0) {
            return ResultModel.checkParamFail();
        }
        Goods goodsModel = goodsBaseService.getOn(request.getGoodsId());
        AssertUtil.nonNull(goodsModel, ResultEnum.PARAM_CHECK, "产品已下架");

        List<String> photos = goodsPhotoService.getListPath(request.getGoodsId());
        List<GoodSpec> specs = goodsBaseService.getSpecs(request.getGoodsId());
        List<GoodsInfoResponse.Spec> goodSpecModelList = Lists.newArrayList();
        int i = -1;
        if (OneListUtil.isNotEmpty(specs)) {
            for (GoodSpec spec : specs) {
                if (spec.getParentId() > 0) {
                    goodSpecModelList.get(i).getGoodSpecModelList().add(GoodsInfoResponse.Spec.builder()
                            .specId(spec.getSpecId())
                            .parentId(spec.getParentId())
                            .specName(spec.getSpecName())
                            .specAttribute(spec.getSpecAttribute())
                            .price(Objects.nonNull(spec.getPriceRemark()) ? MoneyUtil.getMoneyInt(spec.getPriceRemark()) : spec.getPrice())
                            .specNum(spec.getSpecNum())
                            .build());
                } else {
                    goodSpecModelList.add(GoodsInfoResponse.Spec.builder()
                            .specId(spec.getSpecId())
                            .parentId(spec.getParentId())
                            .specName(spec.getSpecName())
                            .specAttribute(spec.getSpecAttribute())
                            .goodSpecModelList(Lists.newArrayList())
                            .build());
                    i++;
                }
            }
        }

        GoodsInfoResponse response = GoodsInfoResponse.builder()
                .showPrice(goodsModel.getShowPrice())
                .qjVrUrl(goodsModel.getQjVrUrl())
                .goodsDetails(goodsModel.getGoodsDetails())
                .goodsName(goodsModel.getGoodsName())
                .price(MoneyUtil.getMoneyInt(goodsModel.getPrice()))
                .coverImg(goodsModel.getCoverImg())
                .ispayment(goodsModel.getIsPayment())
                .videoUrl(goodsModel.getVideoUrl())
                .companyId(goodsModel.getCompanyId())
                .goodPhoto(StringUtils.join(photos, OneConstant.arraySymbol))
                .goodSpecModelList(goodSpecModelList)
                .build();

        if (Objects.nonNull(request.getCardId())) {
            BusinessCard businessCardModel = businessCardBaseService.getCustomer(request.getCardId());
            if (Objects.nonNull(businessCardModel)) {
                response.setCardUserId(businessCardModel.getUserId());
            }
        }

        boolean fal = !"1".equals(request.getRefresh())
                && request.getGoodsId() != null
                && (request.getMyCardId() == null || !request.getMyCardId().equals(request.getCardId()));
        if (fal) {
            //添加查看记录
            SeeRecordGoodsRequest recordGoodsRequest = SeeRecordGoodsRequest.builder()
                    .userId(request.getId())
                    .cardId(request.getCardId())
                    .companyId(goodsModel.getCompanyId())
                    .itemId(request.getGoodsId())
                    .build();
            seeRecordFeign.goods(recordGoodsRequest);
        }

        logger.info("end getGoodsInfo");
        return ResultModel.success(response);
    }

    @PostMapping("/goodsCard")
    @ApiOperation(value = "获取产品海报")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "specId", value = "商品类型id", required = true, paramType = "Integer"),
    })
    @SecurityAuthCheck
    public ResultModel goodsCard(@RequestAttribute GoodGoodsCardRequest request) {
        AssertUtil.nonNull(request.getCardId(), ResultEnum.PARAM_CHECK);
        AssertUtil.nonNull(request.getSpecId(), ResultEnum.PARAM_CHECK);
        GoodSpec goodSpec = goodSpecMapperExt.selectByPrimaryKey(request.getSpecId());

        TemplateGet2Request getRequest = TemplateGet2Request.builder()
                .templateType(TemplateApi.Type.ID_CRM_APP_GOODS)
                .cardId(request.getCardId())
                .goodsId(goodSpec.getGoodsId())
                .build();
        ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get2(getRequest);
        AssertUtil.isTrue(getResponseResultModel);
        String cardUrl = getResponseResultModel.getData().getImageUrl();
        return ResultModel.success(cardUrl);
    }
}
